import axios from "axios";

const $axios = axios.create({
  baseURL: "http://192.168.124.9:8888", // 基础 URL
  timeout: 5000, // 设置时间为 5 秒
});

// 请求拦截器
$axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; // 添加 Authorization 头
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
$axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      // 未授权，跳转到登录页面
      localStorage.removeItem("token");
      localStorage.removeItem("username");
      localStorage.removeItem("permissions");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default $axios;
